// 导入必要的React hooks
import { useState, useEffect } from 'react';

// 主题类型定义
type Theme = 'gradient';

export function useTheme() {
  // 默认使用粉蓝渐变主题
  const [theme, setTheme] = useState<Theme>('gradient');
  
  // 深色模式状态 - 在初始化时就尝试从localStorage读取设置
  const [isDark, setIsDark] = useState<boolean>(() => {
    try {
      // 直接检查系统偏好和localStorage
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      const savedDarkMode = localStorage.getItem('isDark');
      
      // 如果有保存的设置，使用保存的设置，否则使用系统偏好
      const initialDarkMode = savedDarkMode !== null ? savedDarkMode === 'true' : prefersDark;
      
      // 立即应用初始深色模式设置
      if (initialDarkMode) {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
      
      return initialDarkMode;
    } catch (error) {
      console.error('Error initializing dark mode:', error);
      return false;
    }
  });
  
  // 当isDark状态变化时，同步到document和localStorage
  useEffect(() => {
    try {
      if (isDark) {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
      localStorage.setItem('isDark', isDark.toString());
    } catch (error) {
      console.error('Error updating dark mode:', error);
    }
  }, [isDark]);
  
  // 监听系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handleChange = (e: MediaQueryListEvent) => {
      // 只有在用户没有明确设置偏好时才跟随系统变化
      const savedDarkMode = localStorage.getItem('isDark');
      if (savedDarkMode === null) {
        setIsDark(e.matches);
      }
    };
    
    mediaQuery.addEventListener('change', handleChange);
    
    return () => {
      mediaQuery.removeEventListener('change', handleChange);
    };
  }, []);
  
  // 切换深色/浅色模式
  const toggleDarkMode = () => {
    setIsDark(prev => !prev);
  };

  return {
    theme,
    isDark,
    toggleDarkMode
  };
}